package example.controller;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.tanesha.recaptcha.ReCaptchaImpl;
import net.tanesha.recaptcha.ReCaptchaResponse;

public class Recapcha extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
		throws IOException {
		
		try {
            req.getRequestDispatcher("/pages/recapcha.jsp").forward(req, resp);
        } catch (Exception e) {
            //TODO: handle exception
            e.printStackTrace();
        }
	}
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
		throws IOException {
		String remoteAddr = req.getRemoteAddr();
        ReCaptchaImpl reCaptcha = new ReCaptchaImpl();
        reCaptcha.setPrivateKey("6Lfe2s4SAAAAAB5YROF403KNNTqnB0I15JwDG4aX");

        String challenge = req.getParameter("recaptcha_challenge_field");
        String uresponse = req.getParameter("recaptcha_response_field");
        System.out.println(challenge);
        System.out.println(uresponse);
        ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(remoteAddr, challenge, uresponse);

        if (reCaptchaResponse.isValid()) {
          resp.getWriter().print("Answer was entered correctly!");
        } else {
        	resp.getWriter().print("Answer is wrong");
        }
	}
}
